package com.haiertvbic.tvnow;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.haiertvbic.tvnow.holder.ScreenshortHolder;
import com.haiertvbic.tvnow.model.ProgramBean;
import com.haiertvbic.tvnow.model.ProgramItemBean;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.service.ServiceUtil;
import com.haiertvbic.tvnow.service.SwitchChanellCallback;
import com.haiertvbic.tvnow.util.AppManager;
import com.haiertvbic.tvnow.util.Constant;
import com.haiertvbic.tvnow.util.DensityUtil;
import com.haiertvbic.tvnow.util.LocateToast;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.SetActivityView;

/**
 * 获取节目数据，第二屏
 * 
 * @author sun
 * 
 */
public class TVNOWProgramListActivity extends Activity {
	private Activity context = TVNOWProgramListActivity.this;
	private static final String TAG = "SecondActivity";
	protected static final int GET_PRO_SUC = 01;// 获取节目成功
	protected static final int GET_PRO_FAIL = 02; // 获取节目失败

	private ListView pro_detail_lv;
	private LinearLayout anim2_ll;
	private TextView pro_name_tv;
	private TextView loading_tv;

	private ArrayList<ProgramBean> programList;
	private int channelId;
	private String channelName;
	private int which;
	public static View view;
	private boolean canToNext;
	private int currentCha = -200;
	private int switchCha = -200;
	private boolean canSwitch;
	private int sreen_width;

	private Handler myHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.acitivity_programs_tvnowontv);
		view = SetActivityView.setActivityView(getWindow(), getWindowManager());
		sreen_width = getWindowManager().getDefaultDisplay().getWidth();
		Intent intent = getIntent();
		channelId = intent.getIntExtra("CHA_ID", -1);
		channelName = intent.getStringExtra("CHA_NAME");
		// cha_id = 1;
		// cha_name = "湖南卫视";
		// EPGWeb.initSdcarDir(context);//测试用
		initView();
		AppManager.activityList.add(this);
		Animation inAnimation = AnimationUtils.loadAnimation(this,
				R.anim.slide_in_right);
		anim2_ll.setAnimation(inAnimation);
		anim2_ll.startAnimation(inAnimation);
		SLog.d(TAG, "第一屏传来的频道id是：" + channelId + "频道名字" + channelName);
		getResultPre();
		myHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case GET_PRO_FAIL:
					loading_tv.setVisibility(View.VISIBLE);
					loading_tv.setText(R.string.getProFail);
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.get_program_failed));
					break;
				case GET_PRO_SUC:
					// 获取数据成功，适配显示数据，消失加载数据的进度条
					if (programList != null && programList.size() > 0) {
						loading_tv.setVisibility(View.GONE);
						pro_detail_lv.setAdapter(new ProgramAdapater(programList,
								sreen_width, context));
						pro_detail_lv.setVisibility(View.VISIBLE);
						pro_detail_lv.requestFocus();
					} else {
						loading_tv.setVisibility(View.VISIBLE);
						loading_tv.setText(R.string.getProFail);
					}
					canToNext = true;
					canSwitch = true;
					break;
				case 0:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.read_change_msg_failed));
					break;

				case 4004500:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.change_success));
					currentCha = switchCha;
					try {
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					break;

				case 4004501:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.channel_non_existent));
					break;

				case 4004502:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.please_connect_crb));
					break;

				case 4004503:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.no_set_crb));
					break;

				case -2002:
					LocateToast.locateToast(context, 200, getResources()
							.getString(R.string.connect_break_off));
					break;

				default:
					break;
				}

			}
		};
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		anim2_ll = (LinearLayout) findViewById(R.id.anim2_ll);
		pro_name_tv = (TextView) findViewById(R.id.pro_name_tv);
		pro_name_tv.setText(channelName);
		loading_tv = (TextView) findViewById(R.id.loading_tv);
		pro_detail_lv = (ListView) findViewById(R.id.pro_detail_lv);
		pro_detail_lv.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				which = arg2;
			}

			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		pro_detail_lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (canSwitch && currentCha != channelId) {
					ServiceUtil.changeChannel(context, channelId,
							new SwitchChanellCallback() {

								@Override
								public void returnData(int source,
										int resultCode, int result) {
									myHandler.sendEmptyMessage(resultCode);
								}
							});
					switchCha = channelId;
				}
			}
		});
	}

	/**
	 * 得到节目的过程，开了一个线程和服务器交互获取数据
	 */
	public void getResultPre() {
		new Thread() {
			public void run() {
				try {
					programList = EPGWeb.getProgramList(context, channelId);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if (programList == null) {
					myHandler.sendEmptyMessage(GET_PRO_FAIL);
				} else {
					myHandler.sendEmptyMessage(GET_PRO_SUC);
				}

				// 获取电视剧pType
				try {
					ArrayList<ProgramItemBean> itemList = EPGWeb
							.getProgramItem(context);
					int size = itemList.size();
					for (int index = 0; index < size; index++) {
						ProgramItemBean itemBean = itemList.get(index);
						if (itemBean.getName().equals("电视剧")) {
							Constant.PRO_TYPE = itemBean.getNode() + "";
							break;
						}
					}
				} catch (Exception e) {
					if (Constant.PRO_TYPE == null) {
						myHandler.sendEmptyMessage(GET_PRO_FAIL);
					}
				}
			};
		}.start();

	}
	class ProgramAdapater extends BaseAdapter {
		private ArrayList<ProgramBean> proList;
		private Context context;
		private int sreenWeight;
		private Map<String, SoftReference<Bitmap>> proDetailCaches = new HashMap<String, SoftReference<Bitmap>>();

		public ProgramAdapater(ArrayList<ProgramBean> pro_list, int sreenWeight,
				Context applicationContext) {
			this.proList = pro_list;
			this.context = applicationContext;
			this.sreenWeight = (sreenWeight) / Constant.CHANNEL_NUMBER;// 其实现在是整个屏幕的宽度
		}

		@Override
		public int getCount() {
			SLog.d(TAG, "==========getCount====================");
			return proList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return proList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			SLog.d(TAG, "==========getView====================");
			ScreenshortHolder holder = new ScreenshortHolder();
			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.layout_program_tvnowontv_item, null);
				holder.pip_iv = (ImageView) convertView
						.findViewById(R.id.detail_iv);
				holder.tomorrow = (TextView) convertView.findViewById(R.id.tomorrow_tvnow);
				holder.pro_tv = (TextView) convertView
						.findViewById(R.id.detail_pro_tv);
				holder.pro_stime_tv = (TextView) convertView
						.findViewById(R.id.detail_stime_tv);
				convertView.setTag(holder);
			} else {
				holder = (ScreenshortHolder) convertView.getTag();
			}
			ProgramBean p = proList.get(arg0);
			if (p != null) {
				if (p.getPicurl() != null) {
					String urlStr = p.getPicurl();
					if (proDetailCaches.containsKey(urlStr)
							&& (proDetailCaches.get(urlStr).get() != null)) {
						// 若软引用中有，给image设置
						holder.pip_iv.setImageBitmap(proDetailCaches.get(urlStr)
								.get());
						holder.pip_iv.setVisibility(View.VISIBLE);
					} else {
						// 开异步线程去台标
						new PipAsyncTask(holder.pip_iv).execute(urlStr);
					}
				}
				// 对字体设置===================================
				Calendar c = Calendar.getInstance();
				int week = c.getTime().getDay();
				if (week == 0)
				{
					week = 7;
				}
				String s = p.getPstime() + "c";
				s = s.replace(":00c", "");
				if (p.getPweekday()==(week+1)) {
					holder.tomorrow.setText("    " + context.getResources().getString(R.string.tomorrow));
					holder.tomorrow.setVisibility(View.VISIBLE);
					holder.pro_stime_tv.setText(s);
				}else {
					holder.pro_stime_tv.setText("    " + s);
					holder.tomorrow.setVisibility(View.GONE);
				}
				holder.pro_tv.setText("    " + p.getPn());
			}
			return convertView;

		}

		class PipAsyncTask extends AsyncTask<String, Void, Bitmap> {
			private ImageView pip_iv;

			public PipAsyncTask(ImageView pip_iv) {
				this.pip_iv = pip_iv;
			}

			@Override
			protected Bitmap doInBackground(String... params) {
				String urlStr = params[0];
				Bitmap bm = null;
				SLog.d(TAG, "取得节目信息图片的url===" + urlStr);
				bm = EPGWeb.getBitmapFromURL(context, urlStr);
//				bm =BitmapFactory.decodeResource(context.getResources(), R.drawable.test);
				// 获得Bitmap的高和宽
				if (bm != null) {
					int bmpWidth = bm.getWidth();
					int bmpHeight = bm.getHeight();
					// 如果屏幕的宽度1/5，小于图片的宽度在变更
					if (bmpWidth > sreenWeight) {
						// 产生resize后的Bitmap对象
						float scale = sreenWeight / bmpWidth;
						Bitmap resizeBmp = null;
						if (DensityUtil.dip2px(context, sreenWeight) > 0
								&& DensityUtil.dip2px(context, bmpHeight * scale) > 0) {
							resizeBmp = Bitmap.createScaledBitmap(bm,
									DensityUtil.dip2px(context, sreenWeight),
									DensityUtil.dip2px(context, bmpHeight * scale),
									true);
							proDetailCaches.put(urlStr, new SoftReference<Bitmap>(
									resizeBmp));
							bm = resizeBmp;
							SLog.d(TAG, "算出后的图片宽是====" + resizeBmp.getWidth());
							SLog.d(TAG, "算出后的图片高是====" + resizeBmp.getHeight());
						}
					}
					SLog.d(TAG, "图片宽是====" + bmpWidth);
					SLog.d(TAG, "图片高是====" + bmpHeight);
				}
				SLog.d(TAG, "====doInBackground============获取到节目详情图片了");
				return bm;
			}

			@Override
			protected void onPostExecute(Bitmap result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (result != null) {
					pip_iv.setImageBitmap(result);
					pip_iv.setVisibility(View.VISIBLE);
				}
			}
		}
	}

	/**
	 * 处理按键事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// ProduceThread.seconds = 60;
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			Intent intent = new Intent();
			intent.setClass(context, TVNOWMainActivity.class);
			finish();
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			// ProduceThread.canRun = false;
			// ProduceThread.exit = false;
			// IsExit.isExit(this);
		} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			if (programList != null && which < programList.size()
					&& programList.get(which).getPtype() != null && canToNext
					&& programList.size() > 0) {

				if (programList.get(which).getPtype().contains(Constant.PRO_TYPE)) {
					Intent intent = new Intent();
					intent.setClass(context, TVNOWProgramStateAcitivity.class);
					intent.putExtra("PRO_ID", programList.get(which).getPid());
					intent.putExtra("PRO_NAME", programList.get(which).getPn());
					startActivity(intent);
					view.setVisibility(View.GONE);
				} else {
					LocateToast
							.locateToast(
									this,
									200,
									getResources()
											.getString(
													R.string.the_pro_is_not_Television_poly));

				}
			}

		}
		return super.onKeyDown(keyCode, event);
	}

}
